import { JwtService } from '@nestjs/jwt';
import { UnauthorizedException } from '@nestjs/common';

export class TokenUtil {
    private static jwtService: JwtService;

    static init(jwtService: JwtService) {
        TokenUtil.jwtService = jwtService;
    }

    static decode(token: string) {
        try {
            // 处理 Bearer token
            const tokenString = token.startsWith('Bearer ')
                ? token.slice(7)
                : token;

            // 解析 token
            const decoded = TokenUtil.jwtService.verify(tokenString);
            return decoded;

        } catch (error) {
            console.log('token decode error:', error);
            throw new UnauthorizedException('无效的认证令牌');
        }
    }

    static getUserId(token: string): number {
        const decoded = this.decode(token);
        return decoded?.id;
    }
} 